package com.qf.service;

import com.qf.constant.CacheConstants;
import com.qf.feign.CacheFeign;
import com.qf.model.StandardSubmit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * projectName: wokepase1
 *
 * @author: 强力
 * time: 2021/10/18 17:36
 * description:
 */
@Service
@Slf4j
public class FilterChainManagerImpl implements FilterChainManager{
    @Autowired
    public CacheFeign cacheFeign;

    @Autowired
    private Map<String,FilerChainService> filerChainMap;

    @Override
    public void execute(StandardSubmit standardSubmit) {
      //1.获取短信客户端id
        Integer clientID = standardSubmit.getClientID();
        //2.远程调用feign远程调用cache模块,根据客户di获取客户对象数据
        Map clentMap = cacheFeign.hMGet(CacheConstants.CACHE_PREFIX_CLIENT + clientID);

        if (clentMap == null) {
            log.info("[策略管理者]调用cache模块获取客户id错误,client={}",clientID);
            return;
        }
        //3.获取缓存数据中客户设置的过滤策略名称和执行顺序字符串
        Object strategyobj = clentMap.get("filters");
        if (strategyobj == null) {
            log.info("[策略管理者]客户没有策略执行设置,客户端id,clientid={}",clientID);
            return;
        }
        //从redis中获取到的客户提前设置的策略,和执行顺序
        String[] strategyArray = String.valueOf(strategyobj).split(",");
        //4.遍历客户设置的策略数组,保证顺序执行
        if (strategyArray != null) {
            for (String strategyName : strategyArray) {
                //5.根据客户设置的需要执行的策略名称和顺序,匹配具体的策略实现类执行
                FilerChainService filerChainService = filerChainMap.get(strategyName);
                //执行策略
                boolean flag = filerChainService.strategy(standardSubmit);

                //判断如果执行失败,则终止,不再执行其他策略
                if (!flag){
                    log.info("[策略管理者]执行顺序错误,客户端id,clientid={},策略名称={}",clientID,strategyName);
                    return;
                }
                log.info("[策略管理者]策略执行成功,客户端id,clientid={},策略名称={}",clientID,strategyName);


            }
        }


    }
}
